package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.product.api.domain.ProductSkuVo;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.IProductSkuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.spzx.product.api.domain.SkuPriceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品sku 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-02-19
 */
@Service
@Slf4j
public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, ProductSku> implements IProductSkuService {

    @Autowired
    public RedisTemplate redisTemplate;

    @Override
    public List<ProductSkuVo> getTopSale() {
        return baseMapper.selectTopSale();
    }

    @Override
    public List<ProductSkuVo> selectProductSkuList(SkuQuery skuQuery) {
        return baseMapper.selectProductSkuList(skuQuery);
    }

    @Override
    public SkuPriceVo getSkuPrice(Long skuId) {
        // 根据skuId查询商品价格
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(ProductSku::getId, skuId)
                .select(ProductSku::getSalePrice, ProductSku::getMarketPrice);
        ProductSku productSku = baseMapper.selectOne(queryWrapper);
        // 封装数据
        SkuPriceVo skuPriceVo = new SkuPriceVo();
        skuPriceVo.setMarketPrice(productSku.getMarketPrice());
        skuPriceVo.setSalePrice(productSku.getSalePrice());
        skuPriceVo.setSkuId(skuId);
        return skuPriceVo;

    }

    @Override
    public Map<String, Long> getSkuSpecValue(Long productId) {
        HashMap<String, Long> map = new HashMap<>();
        LambdaQueryWrapper<ProductSku> lambdaQueryWrapper = new LambdaQueryWrapper<ProductSku>()
                .eq(ProductSku::getProductId, productId)
                .select(ProductSku::getSkuSpec, ProductSku::getId);
        List<ProductSku> productSkuList = baseMapper.selectList(lambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(productSkuList)){
            for (ProductSku productSku : productSkuList) {
                map.put(productSku.getSkuSpec(), productSku.getId());
            }
            return map;
        }
        return null;
    }

    /**
     * 根据skuId查询sku信息
     */
    @Override
    public ProductSku findSkuById(Long skuId) {
        //优先从redis中查询
        String dataKey = "sku:info:"+skuId;
        ProductSku productSku = (ProductSku) redisTemplate.opsForValue().get(dataKey);
        if (productSku != null){
            return productSku;
        }
        //获取分布式锁，如果获取到锁，则从数据库中查询，将查询到的数据放入redis中，释放锁
        String lockKey = dataKey + ":lock";
        String lockValue = UUID.randomUUID().toString();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 3, TimeUnit.SECONDS);
        if (flag){
            try {
                log.info(Thread.currentThread().getName() +"获取锁成功，开始查询商品sku信息");
                productSku = baseMapper.selectById(skuId);
                int ttl = 7200 + new Random().nextInt(2000);
                redisTemplate.opsForValue().set(dataKey, productSku, ttl, TimeUnit.SECONDS);
                return productSku;
            } finally {
                //释放锁
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then\n" +
                        "    return redis.call('del', KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                redisTemplate.execute(
                        new DefaultRedisScript<>(script, Boolean.class),
                        Arrays.asList(lockKey),
                        lockValue);
            }
        }else {
            //获取锁失败，自旋
            try {
                log.error(Thread.currentThread().getName() +"获取锁失败，开始自旋");
                Thread.sleep(500);
                return this.findSkuById(skuId);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public List<SkuPriceVo> getSkuPriceList(List<Long> skuIdList) {
        List<ProductSku> productSkus = baseMapper.selectList(new LambdaQueryWrapper<ProductSku>()
                .in(ProductSku::getId, skuIdList)
                .select(ProductSku::getSalePrice, ProductSku::getId, ProductSku::getMarketPrice));
        return productSkus.stream().map(productSku -> {
            SkuPriceVo skuPriceVo = new SkuPriceVo();
            skuPriceVo.setSkuId(productSku.getId());
            skuPriceVo.setSalePrice(productSku.getSalePrice());
            return skuPriceVo;
        }).collect(Collectors.toList());
    }


}
